<template>
  <div>
    <div class="top">
      <Input type="text" v-model="form.title" placeholder="请输入标题" style="width: 230px;"></Input>
      <Select placeholder="请输入标签名" v-model="form.tagName" style="margin-left: 10px">
        <Option v-for="(item, index) in tagNameList" :value="item.tagName" :label="item.tagName" :key="item._id"></Option>
      </Select>
      <Select placeholder="请输入分类名" v-model="form.cgyName" style="margin-left: 10px">
        <Option v-for="(item, index) in cgyNameList" :value="item.cgyName" :label="item.cgyName" :key="item._id"></Option>
      </Select>
      <Button type="success" style="margin-left: 10px;" v-if="!update_id" @click="postArt">发布</Button>
      <Button type="success" style="margin-left: 10px;" v-else @click="edit">修改</Button>
      <Button type="success" style="margin-left: 10px;" @click="$router.back()">返回</Button>
      <Upload
        :http-request="upload_http"
        :on-change="upload_change"
        :before-upload="upload_before"
        action="admin/exam/upImg"
      >
        <Button type="success" style="margin-top: 10px">点击上传封面图片</Button>
      </Upload>
    </div>
    <div id="main">
      <mavon-editor v-model="form.articleDataForStr" :toolbars="markdownOption" style="margin-left: 10px"/>
    </div>
  </div>
</template>

<script>
import {Input, Select, Option, Button, Upload} from 'element-ui'
import {getTagsFun, getclassifiesFun, addArticle, geArtById, editArticle} from '@/api/api'
import axios from 'axios'

export default {
  data() {
    return {
      value: '',
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: false, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },
      form: {
        title: '',
        cgyName: '',
        tagName: '',
        articleDataForStr: '',
        img: ''
      },
      tagNameList: [],
      cgyNameList: [],
      update_id: ''
    }
  },
  mounted() {
    let id = this.$route.query.id
    this.update_id = id
    if (id) {
      this.getDataContent({id})
    }
    this.getTagAndCgyList()
  },
  methods: {
    async getTagAndCgyList(){
      const res = await getTagsFun()
      if (res.data.code === 1) {
        this.tagNameList = res.data.data
      }else{
        this.$message.warning('请求失败')
      }
      const res2 = await getclassifiesFun()
      if (res2.data.code === 1) {
        this.cgyNameList = res2.data.data
      }else{
        this.$message.warning('请求失败')
      }
    },
    async postArt(){
      let data = {
        tagName: this.form.tagName,
        cgyName: this.form.cgyName,
        title: this.form.title,
        articleDataForStr: this.form.articleDataForStr,
        token: localStorage.getItem('token'),
        img: this.form.img
      }
      const res = await addArticle(data)
      if (res.data.code === 1) {
        this.$message.success('发布成功')
        this.$router.push('/archives')
      }else{
        this.$message.warning(res.data.msg)
      }
    },

    upload_http(file) {
      console.log(file, "upload_http");
      // 创建表单对象
      var from = new FormData();
      // 后端接受参数 ，可以接受多个参数
      from.append("file", this.file);
      from.append("bucket", "dxtoss");
      axios({
        data: from,
        url: "/api/users/profile",
        method: "post"
      })
        .then(res => {
          this.form.img = res.data.path
        })
        .catch(res => {
          console.error(res);
        });
    },
    upload_change(file) {
      this.file = file.raw;
    },
    upload_before(file) {
      console.log(file, "upload_before");
      if (["image/jpeg", "image/png"].indexOf(file.type) == -1) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return false;
      }
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error("上传图片大小不能超过 10MB!");
        return false;
      }
    },
    async getDataContent(data){
      const res = await geArtById(data)
      if (res.data.code === 1) {
        data = res.data.data
        this.form = {
          title: data.title,
          cgyName: data.cgyName,
          tagName: data.tagName,
          articleDataForStr: data.articleDataForStr,
          img: data.img
        }
        
      }
    },
    async edit(){
      var data = {
        id: this.update_id,
        articleDataForStr: this.form.articleDataForStr,
        img: this.form.img,
        token: localStorage.getItem('token'),
        title: this.form.title,
        cgyName: this.form.cgyName,
        tagName: this.form.tagName
      }
      let dataArr = Object.keys(data)
      var isValid = true
      for(let i=0;i<dataArr.length;i++){
        let key = dataArr[i]
        if(!data[key]){
          isValid = false
        }
      }
      if (!isValid) {
        return this.$message.warning('请输入完整信息')
      }
      
      const res = await editArticle(data)
      if (res.data.code === 1) {
        this.$message.success('编辑成功')
        this.$router.back()
      }else{
        this.$message.warning(res.data.msg)
      }

    }
  },
  components: {
    Input,
    Select,
    Option,
    Button,
    Upload
  }
}
</script>

<style lang="scss" scoped>
#main{
  // margin-top: 60px;
  height: 1000px;
}
.top{
  background-color: #fff;
  padding: 10px 20px;
}
</style>